package com.qingxin.sys.verifier.rules;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import com.qingxin.sys.verifier.FormMap;
import com.qingxin.sys.verifier.VerifyMsg;
import com.qingxin.sys.verifier.VerifyRule;

/**
 * 正则表达式验证
 * @author Administrator
 *
 */
public class RegexRule extends VerifyRule {
	
	private String compare;//and/or
	private boolean ignoreCase;
	private String regexp;
	private List<String> regexps;

	public RegexRule() {
		this.compare = "or";
		this.ignoreCase = true;
		this.regexps = new ArrayList<String>();
	}
	
	
	@Override
	public VerifyMsg isValid(String id, String name, String label, FormMap formMap) {
		String value = formMap.getParameter(name);
		if(regexps.size()==0 || isEmpty(value)){
			return null;
		}
		boolean all = "and".equalsIgnoreCase(compare);
		boolean pass = false;
		for(String reg : regexps){
			boolean valid = Pattern.compile(reg, ignoreCase ? Pattern.CASE_INSENSITIVE : 0).matcher(value).matches();
			if(!all && valid){
				pass = true;
				break;
			}
			if(all && !valid){
				break;
			}
		}
		
		if(!pass){
			String message = createMessage(null, "{name}", label, "{label}", label);
			return new VerifyMsg(id, name, label, this.getClass().getSimpleName(), message);
		}
		
		return null;
	}

	
	@Override
	public Map<String, Object> getRuleCfg(String name, String label) {
		if(regexps.size()==0){
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rtype", "regexp");
		if(!"or".equalsIgnoreCase(compare)){
			map.put("compare", compare);
		}
		if(!ignoreCase){
			map.put("ignoreCase", ignoreCase);
		}
		map.put("regexps", regexps);
		
		String errormsg = createMessage(null, "{name}", label, "{label}", label);
		if(!isEmpty(errormsg)){
			map.put("error", errormsg);
		}
		
		return map;
	}
	
	
	@Override
	protected void handleRuleArg(String arg) {
		super.handleRuleArg(arg);
		if("i".equals(arg)){
			setIgnoreCase(true);
		}else if("I".equals(arg)){
			setIgnoreCase(false);
		}else if("a".equals(arg)){
			setCompare("and");
		}else if("o".equals(arg)){
			setCompare("or");
		}
	}


	public String getCompare() {
		return compare;
	}
	public void setCompare(String compare) {
		this.compare = compare;
	}
	public boolean isIgnoreCase() {
		return ignoreCase;
	}
	public void setIgnoreCase(boolean ignoreCase) {
		this.ignoreCase = ignoreCase;
	}
	public String getRegexp() {
		return regexp;
	}
	public void setRegexp(String regexp) {
		this.regexp = regexp;
		regexps.add(regexp);
	}
	public List<String> getRegexps() {
		return regexps;
	}
	public void setRegexps(List<String> regexps) {
		this.regexps = regexps;
	}
	public void addRegexp(String regexp) {
		regexps.add(regexp);
	}
	
	
}
